<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>在线选发言人</title>
  <style>
    table {
      width: 100%;
      border-collapse: collapse;
    }
    th, td {
      border: 1px solid #ccc;
      padding: 8px;
      text-align: left;
    }
    th {
      background-color: #f2f2f2;
    }
    .speakerCheckbox {
      margin-right: 10px;
    }
  </style>
</head>
<body>

<h1>在线选择发言人</h1>

<table id="speakersTable">
  <thead>
  <tr>
    <th><input type="checkbox" onclick="toggleCheckAll(this)">全选</th>
    <th>姓名</th>
    <!-- 添加其他列如：年龄、职位等 -->
  </tr>
  </thead>
  <tbody id="speakersData">
  <!-- 动态生成的数据行将放在这里 -->
  </tbody>
</table>

<button onclick="selectRandomSpeaker()">随机选择（最大等待时间5秒）</button>

<script>
  // 候选人信息数组
  var candidates = [
    {name: "张三", age: 30},
    {name: "李四", age: 28},
    {name: "王五", age: 32},
    // 更多候选人...
  ];

  function populateTable() {
    const tableBody = document.getElementById('speakersData');
    tableBody.innerHTML = '';
    candidates.forEach(candidate => {
      const row = `
                <tr>
                    <td><input type="checkbox" class="speakerCheckbox"></td>
                    <td>${candidate.name}</td>
                    <!-- 其他列内容 -->
                </tr>
            `;
      tableBody.insertAdjacentHTML('beforeend', row);
    });
  }

  populateTable();

  // 全选/反选函数
  function toggleCheckAll(masterCheckbox) {
    const checkboxes = document.querySelectorAll('#speakersData .speakerCheckbox');
    checkboxes.forEach(checkbox => checkbox.checked = masterCheckbox.checked);
  }

  // 随机选择一个候选人为发言人，带有最大等待时间
  function selectRandomSpeaker() {
    let maxWaitTimeMs = 5000; // 最大等待时间5秒
    const uncheckedBoxes = Array.from(document.querySelectorAll('#speakersData .speakerCheckbox:not(:checked)'));

    if (uncheckedBoxes.length > 0) {
      const randomIndex = Math.floor(Math.random() * uncheckedBoxes.length);
      const randomTimeout = Math.floor(Math.random() * maxWaitTimeMs);

      setTimeout(() => {
        uncheckedBoxes[randomIndex].checked = true;
        alert(`已随机选择发言人：${uncheckedBoxes[randomIndex].parentNode.parentNode.cells[1].textContent}`);
      }, randomTimeout);
    } else {
      alert('所有候选人均已选中，请先取消部分选择');
    }
  }

  // 示例：动态添加或删除候选人
  function addCandidate(name, age) {
    candidates.push({name, age});
    populateTable();
  }

  function removeCandidate(name) {
    const index = candidates.findIndex(c => c.name === name);
    if (index !== -1) {
      candidates.splice(index, 1);
      populateTable();
    }
  }
</script>

</body>
</html>
